package com.ponhu.ea2.stockcenter.provider.service.rpc.impl;

import com.ponhu.ea2.stockcenter.dto.OrderInfoDTO;
import com.ponhu.ea2.stockcenter.dto.OrderInventoryInfo;
import com.ponhu.ea2.stockcenter.enums.DefinedSystem;
import com.ponhu.ea2.stockcenter.provider.decorators.Idempotence;
import com.ponhu.ea2.stockcenter.provider.service.biz.stocksales.SalesLevelStockResponseService;
import com.ponhu.ea2.stockcenter.provider.support.enums.StockChangeInnerEventEnum;
import com.ponhu.ea2.stockcenter.provider.support.service.RabbitMQService;
import com.ponhu.ea2.stockcenter.service.bms.StockForPurchaseCenterService;
import com.ponhu.ea2.stockcenter.vo.OrderOccupyInfoVO;
import com.ponhu.ea2.stockcenter.vo.ReturnResponseBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Slf4j
@DubboService(version = "1.0.0", interfaceClass = StockForPurchaseCenterService.class, timeout = 60000)
public class StockForPurchaseCenterServiceImpl implements StockForPurchaseCenterService {

    @Autowired
    private SalesLevelStockResponseService salesLevelStockResponseService;

    @Autowired
    protected RabbitMQService rabbitMQService;

    @Idempotence
    @Override
    public ReturnResponseBean<OrderOccupyInfoVO> purchaseReturnApplyOccupyStock(String stockRequestToken, OrderInfoDTO orderInfoDTO) {

        ReturnResponseBean<OrderOccupyInfoVO> returnResponseBean = salesLevelStockResponseService
                .orderOccupyStockHandler(stockRequestToken, orderInfoDTO, DefinedSystem.PURCHASE_CENTER, StockChangeInnerEventEnum.PURCHASE_RETURN_APPLY);

        // 销售库存变动发送MQ
        CompletableFuture.runAsync(() -> {
            List<String> inventoryCodeList = orderInfoDTO.getOrderInventoryInfoList()
                    .stream().map(OrderInventoryInfo::getInventoryCode).collect(Collectors.toList());
            rabbitMQService.saleStockChangeSendMsg(inventoryCodeList);
        });

        return returnResponseBean;
    }

    @Idempotence
    @Override
    public ReturnResponseBean cancelPurchaseReturnApplyOccupyStock(String stockRequestToken, String orderNo) {

        ReturnResponseBean returnResponseBean = salesLevelStockResponseService
                .cancelOrderOccupyStockHandler(stockRequestToken, orderNo, DefinedSystem.PURCHASE_CENTER, StockChangeInnerEventEnum.CANCEL_PURCHASE_RETURN_APPLY);

        // 销售库存变动发送MQ
        CompletableFuture.runAsync(() -> rabbitMQService.saleStockChangeSendMsg(orderNo));

        return returnResponseBean;
    }

}
